<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/26
 * Time: 17:00
 */

namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class ProductController extends ActiveController
{

    public $modelClass = 'zhtfrontend\models\datas\goods';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionView($id)
    {
        $data = $this->findById($id);
        if (ArrayHelper::keyExists('result', $data)) {
            return $data;
        }
        return [
            'items' => [
                'img' => '',
                'title' => empty($data) ? '' : $data['title'],
                'price' => empty($data) ? '' : $data['price'],
                'description' => empty($data) ? '' : $data['description'],
                'status' => '有货,请到对应线下超市购买'
            ]
        ];
    }

    public function findById($id)
    {
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne($id);
        if ($model != null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }

}